import React from 'react';
import ReactDOM from 'react-dom';
import "./css/RaSearch.less";

import {Card, CardActions, CardHeader, CardText} from 'material-ui/Card';
import RaisedButton from 'material-ui/RaisedButton';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import Snackbar from 'material-ui/Snackbar';

import { MuiDataTable } from 'mui-data-table';

// import RaPagination from './RaPagination.jsx';

// import {
//   Table,TableBody,TableHeader,TableFooter,
//   TableHeaderColumn,TableRow,TableRowColumn,
// } from 'material-ui/Table';

import RaUtil from './RaUtil.js';
import Truedata from 'truedata-js';
let truedata = new Truedata.Api();

let PER_PAGE_NUMS = [
    {"key": "per-page-10","label": '10条',"value": 10},
    {"key": "per-page-15","label": '15条',"value": 15},
    {"key": "per-page-20","label": '20条',"value": 20},
    {"key": "per-page-30","label": '30条',"value": 30},
    {"key": "per-page-50","label": '50条',"value": 50},
];
// 刷新时间间隔
let REFRESH_INTERVAL;
class RaEditor extends React.Component {
    constructor(props) {
        super();
        this.state = {
            raReady: props.raReady,
            ra: props.raReady.ra,
            initOption: props.raReady.initOption,
            queryOption: props.raReady.queryOption,
            snackbarOpen: false,
            snackbarMsg: '',
            autoHideDuration: 4000,
            data:{},
            total: 0,       // 数据总数
            tableHeight: '300px',
            fixedHeader: true,
            fixedFooter: true,
            showCheckboxes: props.raReady.initOption.selectAble,
            multiSelectable: (props.raReady.initOption.selectType == 'checkbox'?true:false),
            currentPage: 1, // 当前页数
            perPageNum: 10,  // 条数
            resultHtml:[],
            mainSdName: '',
            search:{},
            selectedData:[]
        }
        // 监听切换查询数据
        this.handleChange = this.handleChange.bind(this);
        // 查询数据
        this.queryData = this.queryData.bind(this);
        // 选择每页条数
        this.selectPerPageNumber = this.selectPerPageNumber.bind(this);
        // 导入
        this.handleImport = this.handleImport.bind(this);
        // 取消
        this.handleCancel = this.handleCancel.bind(this);
    }
    // 导入
    handleImport(){
        return this.state.selectedData;
    }
    // 取消
    handleCancel(){
        // TODO
    }
    // 选中行
    handleSelectedRow(_this,selectedRows){
        let selected = [],
            resultData = this.state.data.data['node'];
        // 选中全部
        if(selectedRows == 'all'){
            selected = RaUtil.cloneObject(resultData);
        }else{
            for(let i = 0; i < resultData.length; i++){
                let curNode = resultData[i];
                if(selectedRows.indexOf(i)>-1){
                    selected.push(curNode);
                }
            }
        }
        this.setState({selectedData:selected});
    }
    // 选择每页条数
    selectPerPageNumber(event, index, value){
        // 切换至首页
        this.state.raReady.queryOption.skip = 0;
        // 每页条数变更
        this.state.raReady.queryOption.limit = value;
        // 查询数据
        this.queryData();
    }
    // 查询数据
    queryData(){
        let queryOption = RaUtil.cloneObject(this.state.queryOption);
        let searchKeys = Object.keys(this.state.search);
        if(searchKeys){
            queryOption.params = {};
            for(let curSearch of searchKeys){
                if(curSearch == 'nodeName'){
                    queryOption.nodeName = this.state.search[curSearch];
                }else{
                    queryOption.params[curSearch] = this.state.search[curSearch];
                }
            }
        }
        // 查询
        if(!queryOption.nodeName){
            this.setState({snackbarMsg: '请选择节点类型后查询！',snackbarOpen: true});
            this.closeSnackbar();
            return;
        }
        this.setState({'mainSdName': queryOption.nodeName});
        truedata.uxdf.query(
        	queryOption,
        	(err,result)=>{
                if(err){
                    this.setState({snackbarMsg: err.message,snackbarOpen: true});
                    this.closeSnackbar();
                    return;
                }
                this.setState({'total': result.totalNum,
                                'data': result.data})
                this.generateTable(result);
        });
    }
    // 生成表格内容
    generateTable(queryResult){
        let tableHtml = [];
        let resultData = queryResult.data.data,
            resultSd = queryResult.data.sd;
        let tableHeads = [];
        let mainSd = RaUtil.cloneObject(resultSd.node.impl[this.state.mainSdName]);
        if(mainSd){
            let propNames = Object.keys(mainSd.prop);
            for(let curPropName of propNames){
                let curProp = mainSd.prop[curPropName];
                curProp.name = curPropName;
                tableHeads.push(curProp);
            }
        }

        let headHtml = [];
        let columnsHtml = [];
        for(let curProp of tableHeads){
            let curKey = curProp.name + '-head',
                _title = curProp.title?curProp.title:curProp.name;
            columnsHtml.push(<TableHeaderColumn
                                key={curKey}
                                tooltip={_title}>{_title}</TableHeaderColumn>);
        }
        headHtml.push(<TableRow key="tab-head">{columnsHtml}</TableRow>);
        tableHtml.push(<TableHeader
                            key="tab-head"
                            displaySelectAll={this.state.showCheckboxes}
                            adjustForCheckbox={this.state.showCheckboxes}>
                            {headHtml}
                        </TableHeader>)
        let bodyHtml = [];
        for(let i=0; i < resultData.node.length; i++){
            let curNode = resultData.node[i],
                _columnsHtml = [];
            if(curNode.__sd == this.state.mainSdName){
                for(let j = 0; j < tableHeads.length; j++){
                    let curKey = i +'-'+ j +'-body',
                        _title = curNode[tableHeads[j].name];
                    _columnsHtml.push(<TableRowColumn
                                        key={curKey}
                                        tooltip={_title}>{_title}</TableRowColumn>);
                }
            }
            let columnKey = 'body-'+ i;
            bodyHtml.push(<TableRow key={columnKey}>{_columnsHtml}</TableRow>);
        }
        tableHtml.push(<TableBody
                            key="tab-body"
                            displayRowCheckbox={this.state.showCheckboxes}
                            striped={true}>
                            {bodyHtml}
                        </TableBody>);
        // 分页
        let footerHtml = this.generatePagination(tableHeads.length);
        tableHtml.push(<TableFooter
                            key="tab-footer">
                            <TableRow>
                                {footerHtml}
                            </TableRow>
                        </TableFooter>);
        this.setState({resultHtml: tableHtml});
    }
    // 生成分页
    generatePagination(colNum){
        let footerHtml = [];
        let paginationKey = 'tab-pagination';
        footerHtml.push(<TableRowColumn
                            key={paginationKey}
                            colSpan={colNum - 1}
                            style={{textAlign: 'right'}}>
                            <RaPagination
                                currentPage={(this.state.total > 0)?this.state.currentPage:0}
                                totalPages={Math.ceil(this.state.total/this.state.perPageNum)}
                                boundaryPagesRange={this.state.boundaryPagesRange}
                                siblingPagesRange={this.state.siblingPagesRange}
                                hidePreviousAndNextPageLinks={false}
                                hideFirstAndLastPageLinks={true}
                                hideEllipsis={false}
                                onChange={this.changePageFromPagination}/>
                        </TableRowColumn>);
        // 切换条数
        let parPageNumberKey = 'tab-pagination-num';
        footerHtml.push(<TableRowColumn
                            key={parPageNumberKey}
                            style={{textAlign: 'left'}}>
                            <SelectField
                                value={this.state.perPageNum}
                                style={{width:100,display:"block",fontSize:"14px"}}
                                onChange={this.selectPerPageNumber.bind(this)}>
                               {PER_PAGE_NUMS.map((pageNum) =>
                                    <MenuItem key={pageNum.key} value={pageNum.value} primaryText={pageNum.label} />)}
                            </SelectField>
                        </TableRowColumn>);
        return footerHtml;
    }
    closeSnackbar(){
        setTimeout(()=>{
            this.setState({snackbarOpen:false});
        },4000);
    }
    handleChange(){
        let curOption = arguments[0],
            curValue = arguments[1].key;
        this.state.search[curOption.key] = curValue;
        this.forceUpdate();
    }
    // 生成查询 html
    generateSearchHtml(searchOptions){
        let searchHtml = [];
        for(let curOption of searchOptions){
            if(curOption.type == 'select'){
                let curValueKey = curOption.key + '-value';
                let curItems = [];
                curOption.options.map((subItem,subIndex) => {
                    curItems.push(<MenuItem
                                    key={curValueKey+'-'+ subIndex}
                                    primaryText={subItem.name}
                                    value={subItem.key}
                                    onClick={this.handleChange.bind(this,curOption,subItem)}/>);
                })
                searchHtml.push(<SelectField
                                    className="search-item"
                                    hintText={curOption.label}
                                    key={curValueKey}
                                    value={this.state.search[curOption.key]}>
                                    {curItems}
                                </SelectField>);
            }
        }
        return searchHtml;
    }
    render() {
        // 查询项
        let searchHtml = [];
        if(this.state.initOption){
            // 提取查询项
            let searchOptions = RaUtil.extractSeachOption(this.state.initOption);
            // 生成查询 html
            searchHtml = this.generateSearchHtml(searchOptions);
            if(searchHtml.length){
                let searchKey = 'search-btn';
                searchHtml.push(<div className="search-item" style={{verticalAlign: 'top'}}>
                                    <RaisedButton
                                        key={searchKey}
                                        primary={true} label="查询"
                                        onClick={this.queryData.bind(this)}/>
                                </div>);
            }
        }
        // 消息提示
        let messageHtml = [];
        // 添加消息提示框
        messageHtml.push(<Snackbar
                          key="search-snackbar"
                          open={this.state.snackbarOpen}
                          message={this.state.snackbarMsg}
                          autoHideDuration={this.state.autoHideDuration}/>);
        return (<div>
                    <Card>
                        <CardHeader
                            title="数据查询"
                            subtitle="选择查询结构后导入"/>
                        <CardText>
                            {searchHtml}
                        </CardText>
                        <CardText>
                            <Table height={this.state.tableHeight}
                                   fixedHeader={this.state.fixedHeader}
                                   fixedFooter={this.state.fixedFooter}
                                   selectable={this.state.showCheckboxes}
                                   multiSelectable={this.state.multiSelectable}
                                   onRowSelection={(selectedRows)=>{this.handleSelectedRow(this,selectedRows)}}>
                                {this.state.resultHtml}
                            </Table>
                        </CardText>
                        <CardActions
                            style={{textAlign:'right'}}>
                            <RaisedButton label="取消" onClick={this.handleCancel.bind(this)}/>
                            <RaisedButton primary={true} label="导入"  onClick={this.handleImport.bind(this)}/>
                        </CardActions>
                    </Card>
                    {messageHtml}
                </div>);
    }
    // 挂载完成
    componentDidMount(){
        REFRESH_INTERVAL = setInterval(()=>{
            if(this.state.raReady.ra){
                // 查询数据
                this.queryData();
                clearInterval(REFRESH_INTERVAL);
            }
        },300);
    }
}
export default RaEditor;
